<template>
	<cl-crud :ref="setRefs('crud')" @load="onLoad">
		<el-row type="flex" align="middle">
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<cl-multi-delete-btn />
			<cl-export-btn type="success" :columns="table.columns" />
			<cl-flex1 />
			<!-- 关键字搜索 -->
			<cl-search-key />
		</el-row>
		<el-row>
			<cl-filter label="扣课类型">
				<el-select
					size="mini"
					filterable
					disabled
					v-model="form.class_type"
					@change="searchSubmit"
					style="width: 20px"
				>
					<el-option :key=1 :value=1 label="班级扣课"></el-option>
					<el-option :key=2 :value=2 label="学生扣课"></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="教师">
				<el-select
					size="mini"
					filterable
					v-model="form.teacher"
					@change="searchSubmit"
					style="width: 20px"
				>
					<el-option :key="all" :value="null" label="全部"></el-option>
					<el-option
						v-for="item in teacher_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			<cl-filter label="学生">
				<el-select
					size="mini"
					filterable
					v-model="form.student"
					@change="searchSubmit"
					style="width: 20px"
				>
					<el-option :key="all" :value="null" label="全部"></el-option>
					<el-option
						v-for="item in student_list"
						:key="item.value"
						:value="item.value"
						:label="item.label"
					></el-option>
				</el-select>
			</cl-filter>
			
			<cl-filter label="上课日期段">
				<el-date-picker
					v-model="form.class_date"
					type="daterange"
					unlink-panels
					@change="searchSubmit"
					size="mini"
					range-separator="到"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					start-placeholder="选择开始日期"
					end-placeholder="选择结束日期"
					:shortcuts="shortcuts"
				>
				</el-date-picker>
			</cl-filter>
			<cl-flex1 />
			<el-button size="mini" type="success" @click="resetSerach">重置</el-button>
		</el-row>
		<el-row>
			<!-- 数据表格 -->
			<cl-table :ref="setRefs('table')" v-bind="table" >
				<template #column-class_date="{ scope }">
					<el-tag size="mini">{{ scope.row.class_date.slice(0, 11) }}</el-tag>
				</template>
				<template #column-class_students="{ scope }">
					<el-tag
						size="mini"
						:type="splitType(item) === '1' ? 'warning' : ''"
						v-for="item in splitStr(scope.row.class_students)"
						:key="item"
						>{{ item.slice(1) }}</el-tag
					>
				</template>
			</cl-table>
		</el-row>

		<el-row type="flex">
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</el-row>

		<!-- 新增、编辑 -->
		<cl-upsert :ref="setRefs('upsert')" v-bind="upsert" @opened="onUpsertOpen" @submit="handleUpsertSubmit">

			<template #slot-footer="{ scope }">
				<!-- <span class="dialog-footer"> -->
				<el-button size="mini" type="primary" @click="putInStorage(scope)" v-show="saveAndCoutinue"
					>保存并继续</el-button
				>

				<!-- </span> -->
			</template>

		</cl-upsert>
	</cl-crud>
</template>

<script lang="ts">
import { computed, defineComponent, inject, onMounted, reactive, ref } from "vue";
import { CrudLoad, Upsert, Table } from "cl-admin-crud-vue3/types";
import { useRefs } from "/@/core";
import { ElMessage, ElMessageBox } from "element-plus";
import { uniqueArray } from "/@/core/utils/loeeutils";

export default defineComponent({
	setup() {
		const { refs, setRefs } = useRefs();
		// 请求服务
		const service = inject<any>("service");

		// 计算属性
		const splitStr = computed(() => {
			return function (str) {
				if (str) {
					return str.split(",");
				}
			};
		});

		// 计算属性
		const splitType = computed(() => {
			return function (str) {
				if (str) {
					return str.slice(0, 1);
				}
			};
		});

		// 保存登录用户的关联的教师id
		const teacherId = function () {
			const userInfo = JSON.parse(localStorage.getItem("userInfo")).teacher;
			console.log(userInfo);

			if (userInfo) {
				return userInfo.id;
			} else {
				return null;
			}
		};

		// 自定义筛选
		const form = ref({
			teacher: null,
			teaching_class: null,
			class_date: null,
			student: null,
			// 扣课类型：1、班级扣课；2、学生扣课
			class_type:2
		});

		// 筛选按钮提交
		const searchSubmit = function () {
			refs.value.crud.refresh({ ...form.value });
		};

		// 重置筛选条件

		const resetSerach = function () {
			form.value = {
				teacher: null,
				teaching_class: null,
				class_date: null,
				student: null,
				class_type:2,
			};
			refs.value.crud.refresh({ ...form.value });
		};

		onMounted(() => {
			// 设置默认值
			form.value.teacher = teacherId();
			searchSubmit();
		});

		// 获取课程主题

		const getCourseInfo = async function () {
			console.log(await service.courseSourceService.list());
		};

		const teacher_list = ref<any>([]);

		const getTeacherInfo = async function () {
			const res = await service.teacherService.list();
			// console.log(res,"=====----====");
			const filteredItems = res.filter(item => item.is_work === 1);

			filteredItems.forEach((item) => {
				teacher_list.value.push({
					value: item.id,
					label: item.name,
					type: "danger"
				});
			});
		};
		// 数组去重
		function ArrSet(Arr, id) {
			var obj = {};
			const arrays = Arr.reduce((setArr, item) => {
				obj[item[id]] ? "" : (obj[item[id]] = true && setArr.push(item));
				return setArr;
			}, []);
			return arrays;
		}
		const class_group_list = ref<any>([]);

		const getClassGroupALL = async function () {
			const res = await service.classgroupService.list();
			console.log(res);
			const ret = uniqueArray(res, "id");
			ret.forEach((item) => {
				class_group_list.value.push({
					value: item.id,
					label: item.class_date + item.class_name + item.class_number,
					type: "info"
				});
			});
		};

		const student_list = ref<any>([]);

		const getStudentInfo = async function () {
			const res = await service.studentService.list();
			console.log(res);

			res.forEach((item) => {
				student_list.value.push({
					value: item.id,
					label: item.name+":"+ item.student_id
				});
			});
		};

		const onUpsertOpen =async (data, { submit, done, close }) => {
			// refs.value.teachingClass.getClassGroupInfo({
			// 	class_date: refs.value.upsert.form.teaching_semester,
			// 	class_course_type: refs.value.upsert.form.course_type
			// });
			if (!refs.value.upsert.isEdit){
				saveAndCoutinue.value = true
			}
			else{
				saveAndCoutinue.value = false
			}

			// 打开的时候添加
			console.log(data,'data');
			if (data){
				courseThemeId.value = refs.value.upsert.form.section_theme
				refs.value.upsert.form.course_reflection =await getCourseEndContent(courseThemeId.value)
			}		
		};
		// 处理表单提交的钩子
		const handleUpsertSubmit =async (isEdit, data, { next, done, close }) => {
			// 将新的上课经验替换到这节课的课程上
			await service.courseSourceService.update({id:courseThemeId.value,teacher_experience:refs.value.upsert.form.course_reflection})
			// alert('handleUpsertSubmit')
			done({data})
			next({...data})
			close()
		};

		// 定义班级上课学期
		const class_date_list = ref([]);
		// 获取上课学期
		const getClassDate = async function () {
			const res = await service.base.system.param.list({ keyName: "class_date" });
			// 将json字符串转换为json对象
			let classType = eval("(" + res[0].data + ")");
			classType.forEach((item) => {
				class_date_list.value.push({
					value: "" + item.value,
					label: item.label,
					type: "success"
				});
			});
		};

		// 定义课程类型列表
		const course_type = ref([]);
		// 获取课程类型
		const getCourseType = async function () {
			const res = await service.courseTypeService.list();
			res.forEach((item, index) => {
				course_type.value.push({
					value: item.id,
					label: item.course_id,
					type: "warning"
				});
			});
		};

		onMounted(() => {
			getCourseInfo();
			getTeacherInfo();
			getClassGroupALL();
			getStudentInfo();
			getClassDate();
			getCourseType();
		});

		// 获取当前年份
		const getNowYear = function () {
			let date = new Date();
			date.getFullYear(); //获取完整的年份(4位)
			let season = "";
			if (date.getMonth() + 1 >=2  && date.getMonth() + 1 <= 7) {
				season = "春季";
			}else if ((date.getMonth() + 1 >=9  && date.getMonth() + 1 <= 12) || date.getMonth() + 1 === 1) {
				season = "秋季";
			}
			return date.getFullYear() + "年" + season;
		};

		const shortcuts = [
			{
				text: "Last week",
				value: () => {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
					return [start, end];
				}
			},
			{
				text: "Last month",
				value: () => {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
					return [start, end];
				}
			},
			{
				text: "Last 3 months",
				value: () => {
					const end = new Date();
					const start = new Date();
					start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
					return [start, end];
				}
			}
		];

		// 用来存储当前的课程小节主题的id
		const courseThemeId = ref(null)

		// 通过选择不同的课程小节主题，出现对应的课程小节主题的总结文本
		const getCourseEndContent =async (id)=>{
			const res = await service.courseSourceService.info({id:id})
			return res.teacher_experience
		}

		// 新增、编辑配置
		const upsert = reactive<Upsert>({
			dialog: {
				width: "80%"
			},
			items: [
				{
					prop: "teaching_semester",
					label: "上课学期",
					span: 6,
					value: getNowYear(),
					component: {
						name: "el-select",
						options: class_date_list.value,
						props: {
							placeholder: "请选择上课学期"
						},
						onChange: (value) => {
							// refs.value.teachingClass.getClassGroupInfo({
							// 	class_date: value,
							// 	class_course_type: refs.value.upsert.form.course_type
							// });
						}
					},
					rules: {
						required: true,
						message: "上课学期不能为空"
					}
				},
				{
					prop: "course_type",
					label: "课程类型",
					span: 6,
					component: {
						name: "el-select",
						options: course_type.value,
						props: {
							placeholder: "请选择课程类型"
						},
						onChange: (value) => {
							// refs.value.teachingClass.getClassGroupInfo({
							// 	class_course_type: value,
							// 	class_date: refs.value.upsert.form.teaching_semester
							// });
							refs.value.sectionTheme.getCourseList({
								course_type: parseInt(value)
							});
							refs.value.upsert.form.section_theme = null
						}
					},
					rules: {
						required: true,
						message: "课程类型不能为空"
					}
				},
				{
					prop: "teacher",
					label: "授课教师",
					span: 6,
					value: teacherId(),
					component: {
						name: "el-select",
						options: teacher_list.value,
						props: {
							placeholder: "请选择授课教师"
						}
					},
					rules: {
						required: true,
						message: "授课教师不能为空"
					}
				},
				{
					prop: "class_date",
					label: "上课日期",
					span: 6,
					component: {
						name: "el-date-picker",
						props: {
							placeholder: "请选择上课日期"
						}
					},
					rules: {
						required: true,
						message: "上课日期不能为空"
					}
				},
				{
					prop: "class_type",
					label: "扣课类型",
					span: 6,
					value: 2,
					component: {
						name: "el-select",
						options: [
							{label: '班级扣课', value:1},
							{label: '学生扣课', value:2},
						],
						disabled: true,
						props: {
							placeholder: "请选择扣课类型"
						}
					},
					rules: {
						required: true,
						message: "扣课类型不能为空"
					}
				},
				{
					prop: "section_theme",
					label: "课程主题",
					span: 12,
					component: {
						name: "course_section_theme",
						props: {
							placeholder: "请输入课程主题"
						},
						onChange: async (value) => {
							const res = await	getCourseEndContent(value)
							courseThemeId.value = value
							// alert(value)
							refs.value.upsert.form.course_reflection = res
						},
						ref: setRefs("sectionTheme")
					},
					rules: {
						required: true,
						message: "课程主题不能为空"
					}
				},
				{
					prop: "other_students",
					label: "添加学生",
					span: 6,
					component: {
						name: "el-select",
						options: student_list.value,
						props: {
							filterable: true,
							clearable: true,
							placeholder: "请选择其他班上课学生"
						},
						ref: setRefs("otherStudents"),
						onChange: async (students: any) => {
								// refs.value.otherStudents.blur();

								// return ElMessage(refs.value.teachingClass.currentPlaceholder);

							let res = await refs.value.classStudents.getStudentInfo(students);
							// console.log(res);

							// if (res) {
							// 	refs.value.upsert.form.other_students.splice(
							// 		refs.value.upsert.form.other_students.length - 1,
							// 		1
							// 	);
							// }
						},
						onRemoveTag: (value: any) => {
							let res = refs.value.classStudents.delStudent(value);
						}
					},
					rules: {
						required: false,
						message: "其他班学生不能为空"
					}
				},
				
				{
					prop: "class_students",
					label: "上课学生",
					span: 24,
					component: {
						name: "class_students_detail",
						props: {
							placeholder: "请选择其他班上课学生"
						},
						ref: setRefs("classStudents")
					},
					rules: {
						required: true,
						message: "其他班学生不能为空"
					}
				},
				{
					prop: "course_reflection",
					label: "课程反思",
					span: 24,
					component: {
						name: "el-input",
						props: {
							type: "textarea",
							rows: 5,
							placeholder: "请输入课程反思"
						}
					},
					rules: {
						required: true,
						message: "课程反思不能为空"
					}
				},
				{
					prop: "note",
					label: "备注",
					span: 24,
					component: {
						name: "el-input",
						props: {
							type: "textarea",
							placeholder: "请输入备注"
						}
					}
				}
			],
			op: {
				// hidden:false,
				// saveButtonText: "重置",
				// closeButtonText:'关闭1',
				buttons: ["slot-footer", "save", "close"]
			}
		});

		// 定义课程列表
		// const course_list = ref([]);

		// 获取课程数据并绑定到课程列表
		// const getCourseList = async () => {
		// 	const res = await service.courseSourceService.list();
		// 	console.log(res);

		// 	res.forEach((item) => {
		// 		course_list.value.push({
		// 			value: item.id,
		// 			label: item.section_theme
		// 		});
		// 	});
		// };

		// 加载时调用函数
		onMounted(async () => {
			// await getCourseList();
			// console.log(course_list.value);
		});

		// 表格配置
		const table = reactive<Table>({
			columns: [
				{
					type: "selection",
					width: 60
				},
				{
					type: "index",
					label: "#",
					width: 50
				},
				{
					prop: "section_theme_name",
					label: "小节主题"
				},
				{
					prop: "teacher",
					label: "教师",
					width: 100,
					dict: teacher_list.value
				},
				{
					prop: "class_date",
					label: "上课日期",
					width: 120
				},
				{
					prop: "class_students",
					label: "上课学生"
				},
				{
					label: "操作",
					width: 100,
					type: "op"
				}
			]
		});

		// crud 加载
		function onLoad({ ctx, app }: CrudLoad) {
			// 绑定 service
			ctx.service(service.classTeachingService).done();
			app.refresh();
		}

		// 自定义新增/编辑对话框的操作按钮-再次入库
		const putInStorage =async function (scope: any) {
			// 删除id避免提交时为更新操作
			delete refs.value.upsert.form.id;
			await service.courseSourceService.update({id:refs.value.upsert.form.section_theme,teacher_experience:refs.value.upsert.form.course_reflection})

			

			refs.value.upsert.validate(async (valid) => {
				if (valid) {
					
					const res = await service.classTeachingService.add(
						refs.value.upsert.modelValue
					);
					if (!res) {
						ElMessage(`添加失败:${res}`);
					}

					ElMessage({
						message: "添加成功，请继续添加",
						type: "success"
					});
					// 修改成新增模式
					refs.value.upsert.isEdit = false;

					// 将上课班级重置为空
					console.log(refs.value.upsert,'======');


					// 重置班级学生
					// refs.value.classStudents.resetClassStudentList();


					// 重置其他班学生
					// refs.value.upsert.form.other_students = null;

					// 重置备注
					refs.value.upsert.form.note = null;


					// 重置课程反思
					// refs.value.upsert.form.course_reflection = null;
					console.log(refs.value.upsert, "____+++_++__");

					// 设置标题为新增
					refs.value.upsert.setTitle("新增");
					refs.value.crud.refresh();
					// 将新的上课经验替换到这节课的课程上

				} else {
					ElMessage({
						type: "error",
						message: "数据未填写完整！"
					})
					return false;
				}
			});

			// 获取课程反思数据
			const res = await	getCourseEndContent(refs.value.upsert.form.section_theme)
			console.log(res,"------res");
			
			refs.value.upsert.form.course_reflection = res
		};

		// 设置保存并继续的按钮是否显示
		const saveAndCoutinue = ref(false)
		

	
		return {
			refs,
			setRefs,
			upsert,
			table,
			onLoad,
			onUpsertOpen,
			handleUpsertSubmit,
			splitStr,
			splitType,
			teacher_list,
			class_group_list,
			form,
			resetSerach,
			searchSubmit,
			shortcuts,
			student_list,
			// 继续扣课
			putInStorage,
			saveAndCoutinue,
			
		};
	}
});
</script>
